package com.wtx.fitness.service.impl;

import com.wtx.fitness.entity.Score;
import com.wtx.fitness.entity.SportItem;
import com.wtx.fitness.entity.Student;
import com.wtx.fitness.mapper.ScoreMapper;
import com.wtx.fitness.mapper.SportItemMapper;
import com.wtx.fitness.mapper.StudentMapper;
import com.wtx.fitness.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 成绩服务实现类
 */
@Service
public class ScoreServiceImpl implements ScoreService {

  @Autowired
  private ScoreMapper scoreMapper;

  @Autowired
  private StudentMapper studentMapper;

  @Autowired
  private SportItemMapper sportItemMapper;

  @Override
  public List<Score> getAllScores() {
    return scoreMapper.selectAll();
  }

  @Override
  public Score getScoreById(Integer id) {
    return scoreMapper.selectById(id);
  }

  @Override
  public List<Score> getScoresByStuId(String stuId) {
    return scoreMapper.selectByStuId(stuId);
  }

  @Override
  public List<Score> getScoresByItemId(Integer itemId) {
    return scoreMapper.selectByItemId(itemId);
  }

  @Override
  public List<Map<String, Object>> getScoreMapsByItemId(Integer itemId) {
    // 调用Mapper层的selectByItemIdAsMap方法获取Map格式的成绩数据
    return scoreMapper.selectByItemIdAsMap(itemId);
  }

  @Override
  public List<Map<String, Object>> getPassRateByGender() {
    return scoreMapper.selectPassRateByGender();
  }

  @Override
  public List<Map<String, Object>> getScoreDistribution(Integer itemId) {
    return scoreMapper.selectScoreDistribution(itemId);
  }

  @Override
  @Transactional
  public int addScore(Score score) {
    // 验证学生存在
    Student student = studentMapper.findByStuId(score.getStuId());
    if (student == null) {
      throw new IllegalArgumentException("学生不存在");
    }

    // 验证项目存在
    SportItem sportItem = sportItemMapper.selectById(score.getItemId());
    if (sportItem == null) {
      throw new IllegalArgumentException("项目不存在");
    }

    // 设置性别（从学生信息中获取）
    score.setGender(student.getGender());

    // 判断是否合格
    score.setIsPass(isPassScore(score.getStorageValue(), student.getGender(), sportItem) ? 1 : 0);

    return scoreMapper.insert(score);
  }

  @Override
  @Transactional
  public int batchAddScores(List<Score> scores) {
    if (scores == null || scores.isEmpty()) {
      return 0;
    }

    // 遍历处理每条成绩记录
    for (Score score : scores) {
      // 验证学生存在
      Student student = studentMapper.findByStuId(score.getStuId());
      if (student == null) {
        throw new IllegalArgumentException("学生不存在: " + score.getStuId());
      }

      // 验证项目存在
      SportItem sportItem = sportItemMapper.selectById(score.getItemId());
      if (sportItem == null) {
        throw new IllegalArgumentException("项目不存在: " + score.getItemId());
      }

      // 设置性别（从学生信息中获取）
      score.setGender(student.getGender());

      // 判断是否合格
      score.setIsPass(isPassScore(score.getStorageValue(), student.getGender(), sportItem) ? 1 : 0);
    }

    return scoreMapper.batchInsert(scores);
  }

  @Override
  @Transactional
  public int updateScore(Score score) {
    // 验证成绩记录存在
    Score existingScore = scoreMapper.selectById(score.getId());
    if (existingScore == null) {
      throw new IllegalArgumentException("成绩记录不存在");
    }

    // 如果学生ID发生变化，验证新学生是否存在
    if (score.getStuId() != null && !score.getStuId().equals(existingScore.getStuId())) {
      Student student = studentMapper.findByStuId(score.getStuId());
      if (student == null) {
        throw new IllegalArgumentException("学生不存在");
      }
      // 更新性别
      score.setGender(student.getGender());
    } else {
      // 保持原有性别
      score.setGender(existingScore.getGender());
    }

    // 如果项目ID发生变化，验证新项目是否存在
    Integer itemId = score.getItemId() != null ? score.getItemId() : existingScore.getItemId();
    SportItem sportItem = sportItemMapper.selectById(itemId);
    if (sportItem == null) {
      throw new IllegalArgumentException("项目不存在");
    }

    // 重新计算是否合格（如果分数发生变化）
    if (score.getStorageValue() != null) {
      score.setIsPass(isPassScore(score.getStorageValue(), score.getGender(), sportItem) ? 1 : 0);
    }

    return scoreMapper.update(score);
  }

  @Override
  @Transactional
  public int deleteScore(Integer id) {
    return scoreMapper.deleteById(id);
  }

  @Override
  @Transactional
  public int deleteScoresByStuId(String stuId) {
    return scoreMapper.deleteByStuId(stuId);
  }

  @Override
  public boolean hasScoresByStuId(String stuId) {
    return scoreMapper.hasScoresByStuId(stuId);
  }

  /**
   * 判断成绩是否合格
   * 
   * @param value     成绩值
   * @param gender    性别
   * @param sportItem 体测项目
   * @return 是否合格
   */
  private boolean isPassScore(BigDecimal value, String gender, SportItem sportItem) {
    if (value == null || gender == null || sportItem == null) {
      return false;
    }

    // 单位为秒的项目（如跑步），成绩越小越好，要小于等于标准值才算合格
    boolean isRunningItem = "秒".equals(sportItem.getUnit());

    if ("男".equals(gender) && sportItem.getMalePass() != null) {
      if (isRunningItem) {
        return value.compareTo(sportItem.getMalePass()) <= 0;
      } else {
        return value.compareTo(sportItem.getMalePass()) >= 0;
      }
    } else if ("女".equals(gender) && sportItem.getFemalePass() != null) {
      if (isRunningItem) {
        return value.compareTo(sportItem.getFemalePass()) <= 0;
      } else {
        return value.compareTo(sportItem.getFemalePass()) >= 0;
      }
    }

    return false;
  }
}